package com.example.word.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.dict.R;
import com.example.word.MyApplication;
import com.example.word.adapter.BrowseAdapter;
import com.example.word.adapter.DictAdapter;
import com.example.word.adapter.WordSearchAdapter;
import com.example.word.bean.Browse;
import com.example.word.bean.Dict;
import com.example.word.bean.StudyPlan;
import com.example.word.bean.Word;
import com.example.word.ui.fragment.HomeFragment;
import com.example.word.util.AlwaysMarqueeTextView;
import com.example.word.util.HttpUtils;
import com.example.word.util.KeyBoardUtil;
import com.example.word.util.MessageUtils;
import com.example.word.util.SPUtils;
import com.example.word.util.StringUtils;
import com.example.word.widget.ActionBar;

import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 搜索单词
 */
public class SearchWordActivity extends AppCompatActivity {
    private ActionBar mTitleBar;//标题栏
    private Activity myActivity;
    private RecyclerView recyclerView;
    private WordSearchAdapter wordSearchAdapter;
    private LinearLayout llEmpty;
    private EditText etQuery;//搜索内容
    private ImageView ivSearch;//搜索图标
    private List<Word> wordList;
    private String account;
    private AlwaysMarqueeTextView systemMsg;


    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_word);
        myActivity = this;
        recyclerView = findViewById(R.id.rv_collect_list);
        llEmpty = findViewById(R.id.ll_empty);
        etQuery = findViewById(R.id.et_query);
        ivSearch = findViewById(R.id.iv_search);
        systemMsg = findViewById(R.id.systemMsg);
        mTitleBar = (ActionBar) findViewById(R.id.myActionBar);
        mTitleBar.setData(myActivity, "搜索单词", R.drawable.ic_back, 0, 0, getResources().getColor(R.color.colorPrimary), new ActionBar.ActionBarClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
            }
        });
        // 设置主题
        if (!MainActivity.colorChange) {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        } else {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.myColor));
        }
        //获取控件
        initView();
        //搜索
        ivSearch.setOnClickListener(v -> {
            loadData();//加载数据
        });
        //点击软键盘中的搜索
        etQuery.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                KeyBoardUtil.hideKeyboard(v);//隐藏软键盘
                loadData();//加载数据
                return true;
            }
            return false;
        });

    }

    /**
     * 初始化页面
     */
    private void initView() {
        account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
        LinearLayoutManager layoutManager = new LinearLayoutManager(myActivity);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //=1.3、设置recyclerView的布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //==2、实例化适配器
        //=2.1、初始化适配器
        wordSearchAdapter = new WordSearchAdapter(llEmpty, recyclerView);
        //=2.3、设置recyclerView的适配器
        recyclerView.setAdapter(wordSearchAdapter);
        wordSearchAdapter.setItemListener(new WordSearchAdapter.ItemListener() {
            @Override
            public void ItemClick(Word word) {
                Map<String, String> requestParam = new HashMap<>();
                requestParam.put("word", word.getWord());
                // 调用 API 客户端的方法
                HttpUtils.sendGetRequest("/getWordList", requestParam, myActivity, Word.class, response -> {
                    List<Word> wordList  = response.getDataList();
                    Intent intent = new Intent(myActivity, WordStudyActivity.class);
                    intent.putExtra("wordArray", new String[]{wordList.get(0).getWord()});
                    intent.putExtra("dict", wordList.get(0).getDict());
                    startActivityForResult(intent, 100);
                });
            }
        });
    }

    private void loadData() {
        if ("".equals(account)) {
            systemMsg.setText(LoginActivity.systemMessage);
        } else {
            // 调用 API 客户端的方法
            HttpUtils.sendGetRequest("/getUserStudyPlan", new HashMap<>(), myActivity, StudyPlan.class, response -> {
                // 加载当前用户学习情况 dayTask,todayCount,totalCount, currentUserDict;
                StudyPlan studyPlan = response.getData();
                systemMsg.setText(String.format("系统消息: 您今日学习目标为%s个单词，今日已学习%s个单词，累计学习了%s个单词，继续加油噢！", studyPlan.getDayTask(), studyPlan.getTodayCount(), studyPlan.getTotalCount()));
            });
        }
        String content = etQuery.getText().toString();//获取搜索内容
        if (StringUtils.isNotEmpty(content)) {
            Map<String, String> requestParam = new HashMap<>();
            requestParam.put("wordLike", content);
            // 调用 API 客户端的方法
            HttpUtils.sendGetRequest("/getWordList", requestParam, myActivity, Word.class, response -> {
                wordList = response.getDataList();
                if (wordList != null && wordList.size() > 0) {
                    recyclerView.setVisibility(View.VISIBLE);
                    llEmpty.setVisibility(View.GONE);
                    wordSearchAdapter.addItem(wordList);
                } else {
                    recyclerView.setVisibility(View.GONE);
                    llEmpty.setVisibility(View.VISIBLE);
                }
            });
        } else {
            MessageUtils.show("请输入搜索关键字", myActivity);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

}
